<?php

namespace app\admin\controller\business;

//引入进来基类控制器
use app\common\controller\Backend;

/**
 * 客户公海控制器
 * 涉及表：business、admin、business_receive
 */
class Privatesea extends Backend
{
  //设置关联查询
  // 如果不设置这个，则会出现id冲突
  protected $relationSearch = true;

  //当前模型
  protected $model = null;

  //当前无须登录方法
  protected $noNeedLogin = [];

  //无需鉴权的方法,但需要登录
  protected $noNeedRight = [];

  //构造函数
  public function __construct()
  {
    parent::__construct();

    //将控制器和模型关联
    $this->model = model('Business.Business');
    $this->SourceModel = model('Business.Source');
    $this->ReceiveModel = model('Business.Receive');
    $this->AdminModel = model('Business.Admin');
    $this->RegionModel = model('Business.Region');

    // 性别
    $GenderList = [0 => '保密', 1 => '男', 2 => '女'];

    // 客户来源
    $SourceDate = $this->SourceModel->column('id, name');

    // 交易状态
    $DealList = [0 => '未成交', 1 => '已成交'];

    // 认证状态
    $AuthList = [0 => '未认证', 1 => '已认证'];

    // 赋值数据到模板当中去
    $this->assign([
      'GenderList' => $GenderList,
      'SourceData' => $SourceDate,
      'DealList' => $DealList,
      'AuthList' => $AuthList
    ]);
  }

  // 列表
  public function index()
  {

    //将请求当中所有的参数去除html标签，去掉两边空白
    $this->request->filter(['strip_tags', 'trim']);

    // 判断是否有ajax
    if ($this->request->isAjax()) {
      //获取表格所提交过来筛选和排序的一些参数
      // 偏移量：$offset， 每页显示多少：$limit
      list($where, $sort, $order, $offset, $limit) = $this->buildparams();

      // 表格需要两个返回值参数 总条数，分页的数据
      // 总条数
      $total = $this->model
        ->with(['Source', 'Admin'])
        ->where('adminid', $this->auth->id)
        ->where($where)
        ->order($sort, $order)
        ->count();

      // 每一页展示的数据
      $list = $this->model
        ->with(['Source', 'Admin'])
        ->where('adminid', $this->auth->id)
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();

      // 组装数据
      $result = [
        'total' => $total,
        'rows' => $list,
      ];

      // 返回json格式数据给ajax
      return json($result);
    }

    // 模板渲染
    return $this->view->fetch();
  }

  // 添加
  public function add()
  {

    // 判断是否接收到post请求
    if ($this->request->isPost()) {
      // 接收row前缀的数据，并将其转换为数组
      $row = $this->request->param('row/a');

      // 生成随机密码盐，并加密密码
      $salt = randstr();
      $password = md5($row['mobile'] . $salt);

      // 组装数据
      $data = [
        'nickname' => $row['nickname'],
        'mobile' => $row['mobile'],
        'email' => $row['email'],
        'money' => $row['money'],
        'password' => $password,
        'salt' => $salt,
        'adminid' => $this->auth->id,
        'gender' => $row['gender'],
        'sourceid' => $row['sourceid'],
        'auth' => $row['auth'],
        'deal' => $row['deal'],
      ];

      // 获取省、市、区的数据
      if (!empty($row['code'])) {
        // 查询当前省、市、区的数据
        $parentpath = $this->RegionModel->where('code', $row['code'])->value('parentpath');
        if (!$parentpath) {
          $this->error('所选地区不存在，请重新输入');
        }

        if (!empty($parentpath)) {
          $arr = explode(',', $parentpath);
          $data['province'] = isset($arr[0]) ? $arr[0] : null;
          $data['city'] = isset($arr[1]) ? $arr[1] : null;
          $data['district'] = isset($arr[2]) ? $arr[2] : null;
        }
      }

      // 更新用户表，插入reveive表
      // 开启事务
      $this->model->startTrans();
      $this->ReceiveModel->startTrans();

      // 更新用户表
      $BusinessStatus = $this->model->validate('common/Business/Business')->save($data);

      // 判断是否更新成功
      if ($BusinessStatus === FALSE) {
        // 提示
        $this->error($this->model->getError());
      }

      // 组装receive表的数据
      $ReceiveData = [
        'applyid' => $this->auth->id,
        'status' => 'allot',
        'busid' =>  $this->model->id
      ];

      // 插入reveive表
      $ReceiveStatus = $this->ReceiveModel->save($ReceiveData);

      // 判断是否插入成功
      if ($ReceiveStatus === FALSE) {
        // 回滚到更新
        $this->model->rollback();
        // 提示
        $this->error($this->ReceiveModel->getError());
      }

      if ($ReceiveStatus === FALSE || $BusinessStatus === FALSE) {
        $this->model->rollback();
        $this->ReceiveModel->rollback();
        $this->error('添加失败！！');
      } else {
        // 如果两个都成功，则可以提交了
        $this->model->commit();
        $this->ReceiveModel->commit();
        $this->success('添加成功！！');
      }
    }

    // 模板渲染
    return $this->view->fetch();
  }

  // 编辑
  public function edit($ids = NULL)
  {
    // 判断该用户是否存在
    $row = $this->model->find($ids);
    if (!$row) {
      $this->error(__('未找到当前用户'));
    }

    // 判断是否又post请求过来
    if ($this->request->isPost()) {
      // 接收row前缀的数据，并将其转换为数组
      $params = $this->request->param('row/a');

      // 组装数据
      $data = [
        'id' =>  $ids,
        'nickname' => $params['nickname'],
        'mobile' => $params['mobile'],
        'email' => $params['email'],
        'gender' => $params['gender'],
        'sourceid' => $params['sourceid'],
        'deal' => $params['deal'],
        'auth' => $params['auth'],
        'money' => $params['money']
      ];

      // 判断当前输入的邮箱是否等于数据库的邮箱，判断是否认证
      if ($params['email'] != $row['email']) {
        $data['auth'] = 0;
      }

      // 判断是否有修改密码，不为空说明进行加密重新修改
      if (!empty($params['password'])) {
        $salt = randstr();
        $data['salt'] = $salt;
        $data['password'] = md5($params['password'] . $salt);
      }

      // 修改省、市、区
      if (!empty($row['code'])) {
        // 查询当前省、市、区的数据
        $parentpath = $this->RegionModel->where('code', $row['code'])->value('parentpath');
        if (!$parentpath) {
          $this->error('所选地区不存在，请重新输入');
        }

        if (!empty($parentpath)) {
          $arr = explode(',', $parentpath);
          $data['province'] = isset($arr[0]) ? $arr[0] : null;
          $data['city'] = isset($arr[1]) ? $arr[1] : null;
          $data['district'] = isset($arr[2]) ? $arr[2] : null;
        }
      }

      // 更新用户表
      $result = $this->model->validate("common/Business/Business")->isUpdate(true)->save($data);

      // 判断是否更新成功
      if ($result === FALSE) {
        $this->error($this->model->getError());
        exit;
      }

      $this->success();
    }

    // 处理地区的数据
    $row['regionCode'] = $row['district'] ?: ($row['city'] ?: $row['province']);

    // 赋值数据到模板中
    $this->assign('row', $row);

    // 模板渲染
    return $this->view->fetch();
  }

  //回收到公海
  public function recovery($ids = null)
  {
    $ids = !empty($ids) ?  explode(',', $ids) : [];
    $row = $this->model->column('id');

    foreach ($ids as $item) {
      if (!in_array($item, $row)) {
        $this->error(__('没有找到该用户'));
        exit;
      }
    }
    $ReceiveData = [];
    $businessData = [];
    foreach ($ids as $value) {

      $ReceiveData[] = [
        'applyid' => $this->auth->id,
        'status' => 'recovery',
        'busid' => $value
      ];

      $businessData[] = [
        'id' => $value,
        'adminid' => null
      ];
    }

    $this->model->startTrans();
    $this->ReceiveModel->startTrans();

    // 更新客户表
    $BusinessStatus = $this->model->saveAll($businessData);

    if ($BusinessStatus === FALSE) {
      $this->error($this->model->getError());
    }
    // 插入领取表
    $ReceiveStatus = $this->ReceiveModel->saveAll($ReceiveData);

    if ($ReceiveStatus === FALSE) {
      $this->model->rollback();
      $this->error($this->ReceiveModel->getError());
    }

    if ($ReceiveStatus === FALSE || $BusinessStatus === FALSE) {
      $this->model->rollback();
      $this->ReceiveModel->rollback();
      $this->error('回收失败');
    } else {
      $this->model->commit();
      $this->ReceiveModel->commit();
      $this->success('回收成功');
    }
  }

  // 删除
  public function del($ids = NULL)
  {
    // 查询用户是否存在，并将其转换为数组分开
    $ids = !empty($ids) ?  explode(',', $ids) : [];

    // 查询出用户的指定字段id
    $business = $this->model->column('id');

    // 遍历出所有的id值，判断id是否存在$business里面
    foreach ($ids as $item) {
      if (!in_array($item, $business)) {
        $this->error(__('没有找到该用户'));
        exit;
      }
    }

    // 删除
    $result = $this->model->destroy($ids);

    if ($result === false) {
      $this->error($this->model->getError());
      exit;
    }

    $this->success();
    exit;
  }
}
